package com.yuehuanghun.framework.domain;

import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.Page;

public class PageDTO<T> implements Serializable, Iterable<T>{

    private static final long serialVersionUID = 230005435568709642L;
    
    public static <E> PageDTO<E> empty() {
    	return new PageDTO<E>();
    }
    
    public PageDTO(List<T> content) {
		this.content = content;
	}
    
    private int size;
    
    private int number;
    
    private long totalElements;
    
    private List<T> content;
    /** 装载额外的数据 */
    private Map<String,Object> extraMap;

    public PageDTO() {
		super();
	}

	public PageDTO(List<T> content,long totalElements) {
        this.content = content;
        this.totalElements = totalElements;
    }
	
	public PageDTO(Page<T> page) {
		this(page.getPageNum(), page.getPageSize(), page.getTotal(), page.getResult());
	}
    
    /**
     * 
     * @param number 当前页
     * @param size 每页行数
     * @param totalElements 总行数
     * @param content 内容列表
     */
    public PageDTO(@JsonProperty("number")int number,@JsonProperty("size") int size,@JsonProperty("totalElements") long totalElements,@JsonProperty("content") List<T> content) {
        this.number = number;
        this.size = size;
        this.totalElements = totalElements;
        this.content = content;
    }
    
    public int getTotalPages() {
        if(getTotalElements() == 0) {
            return 0;
        }
        if(size == 0) {
            return 1;
        }
        return getTotalElements() % size == 0 ? (int)(getTotalElements() / size) : (((int)(getTotalElements() / size)) + 1);
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public long getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(long totalElements) {
        this.totalElements = totalElements;
    }

    public List<T> getContent() {
        return content == null ? Collections.emptyList() : content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    public Map<String, Object> getExtraMap() {
        return extraMap;
    }

    public void setExtraMap(Map<String, Object> extraMap) {
        this.extraMap = extraMap;
    }
    
    public boolean isLast() {
        return getNumber() >= getTotalPages();
    }
    
    public boolean isFirst() {
        return getNumber() == 1;
    }
    
    public int getNumberOfElements() {
        return getContent().size();
    }

    @Override
    public Iterator<T> iterator() {
        return getContent().iterator();
    }
}
